﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.Services;
using Galaktika.BI.Extensibility.Dom.Dac;
using Ranet.Olap.Core.Data;
using Ranet.AgOlap.Controls.MemberChoice.ClientServer;
using Ranet.Web.Olap;
using Ranet.Olap.Core;
using Galaktika.BI.Silverlight.Services;
using Ranet.Olap.Core.Providers;
using Microsoft.AnalysisServices.AdomdClient;
//using Ranet.Olap.Core.Compressor;
using System.Configuration;
using Ranet.ZipLib;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands.MemberChoice
{
    public class MemberChoiceCommand : ServerCommand
    {
        bool UseCompress = true;
        private class RanetQueryExecutor : IQueryExecuter
        {
            public RanetQueryExecutor(string connectionString)
            {
                this.Connection = new ConnectionInfo(connectionString, connectionString);
            }

            #region IQueryExecuter Members

            public ConnectionInfo Connection { get; private set; }

            public int ExecuteNonQuery(string query)
            {
                return AdomdQueryExecutor.StaticExecuteNonQuery(this.Connection.ConnectionString, query);
            }

            public CellSetData ExecuteQuery(string query)
            {
                return AdomdQueryExecutor.StaticExecuteQuery(this.Connection.ConnectionString, query);
            }

            #endregion
        }

        public MemberChoiceCommand(InvokeSchema invoker)
            : base(Galaktika.BI.Silverlight.Commands.CommandId.MemberChoiceCommandId)
        {
            if (ConfigurationSettings.AppSettings.AllKeys.Contains("CompressData"))
            {
                String str = ConfigurationSettings.AppSettings["CompressData"];
                try
                {
                    if (!String.IsNullOrEmpty(str))
                        UseCompress = Convert.ToBoolean(str);
                }
                catch (System.FormatException)
                {
                }
            }

            this.Args = XmlUtility.XmlStr2Obj<MemberChoiceQuery>(invoker[KnownInvokeArgs.MemberChoiceQueryInfo]);
        }

        public MemberChoiceQuery Args { get; private set; }

        public override InvokeResultSchema Invoke()
        {
            InvokeResultSchema result = new InvokeResultSchema(base.Id);
            result.ContentType = KnownContentTypes.Empty;
            try
            {
                MemberChoiceQuery args = this.Args;
                String res = String.Empty;
                switch (args.QueryType)
                {
                    case MemberChoiceQueryType.GetRootMembersCount:
                        res = GetRootMembersCount(args);
                        break;
                    case MemberChoiceQueryType.GetRootMembers:
                        res = GetRootMembers(args);
                        break;
                    case MemberChoiceQueryType.GetChildrenMembers:
                        res = GetChildrenMembers(args);
                        break;
                    case MemberChoiceQueryType.FindMembers:
                        res = FindMembers(args);
                        break;
                    case MemberChoiceQueryType.GetAscendants:
                        res = GetAscendants(args);
                        break;
                    case MemberChoiceQueryType.GetMember:
                        res = GetMember(args);
                        break;
                    case MemberChoiceQueryType.GetMembers:
                        res = GetMembers(args);
                        break;
                    case MemberChoiceQueryType.LoadSetWithAscendants:
                        res = LoadSetWithAscendants(args);
                        break;
                }

                result.Content = res;
                if (UseCompress)
                {
                    // Архивация строки
                    String compesed = ZipCompressor.CompressAndConvertToBase64String(res);
                    result.Content = compesed;
                    result.IsArchive = true;
                }
                result.ContentType = KnownContentTypes.MultidimData;
            }
            catch (AdomdConnectionException connection_ex)
            {
                result.ContentType = KnownContentTypes.ADOMDError;
                result.Content = connection_ex.Message;
            }
            catch (AdomdErrorResponseException response_ex)
            {
                result.ContentType = KnownContentTypes.ADOMDError;
                result.Content = response_ex.Message;
            }
            catch
            {
                throw;
            }
            return result;
        }

        String LoadSetWithAscendants(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            List<MemberDataWrapper> members = null;
            members = provider.LoadSetWithAscendants(args.Set, args.CubeName, args.SubCube, args.HierarchyUniqueName);

            return XmlUtility.Obj2XmlStr(members, Common.Namespace);
        }

        String GetMembers(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            List<MemberDataWrapper> members = null;
            members = provider.GetMembers(args.CubeName, args.SubCube, args.Set);

            return XmlUtility.Obj2XmlStr(members, Common.Namespace);
        }

        String GetMember(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            MemberDataWrapper member = null;
            member = provider.GetMember(args.CubeName, args.MemberUniqueName, args.Properties);

            return XmlUtility.Obj2XmlStr(member, Common.Namespace);
        }

        String GetRootMembersCount(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            double count = 0;

            if (String.IsNullOrEmpty(args.StartLevelUniqueName))
                count = provider.GetMembersCount(args.CubeName, args.SubCube, args.HierarchyUniqueName, 0);
            else
                count = provider.GetMembersCount(args.CubeName, args.SubCube, args.HierarchyUniqueName, args.StartLevelUniqueName);

            return count.ToString();
        }

        String GetRootMembers(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            List<MemberDataWrapper> members = null;
            if (String.IsNullOrEmpty(args.StartLevelUniqueName))
                members = provider.GetHierarchyMembers(args.CubeName, args.SubCube, args.HierarchyUniqueName, 0, args.BeginIndex, args.Count);
            else
                members = provider.GetLevelMembers(args.CubeName, args.SubCube, args.HierarchyUniqueName, args.StartLevelUniqueName, args.BeginIndex, args.Count);

            return XmlUtility.Obj2XmlStr(members, Common.Namespace);
        }

        String GetChildrenMembers(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            List<MemberDataWrapper> members = null;
            members = provider.GetChildrenMembers(args.CubeName, args.SubCube, args.HierarchyUniqueName, args.MemberUniqueName, args.BeginIndex, args.Count);

            return XmlUtility.Obj2XmlStr(members, Common.Namespace);
        }

        String FindMembers(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            List<MemberDataWrapper> members = null;
            members = provider.SearchMembers(args.CubeName, args.SubCube, args.HierarchyUniqueName, args.StartLevelUniqueName, args.Filter);

            return XmlUtility.Obj2XmlStr(members, Common.Namespace);
        }

        String GetAscendants(MemberChoiceQuery args)
        {
            OlapProvider provider = new OlapProvider(new RanetQueryExecutor(args.Connection));

            List<MemberDataWrapper> members = null;
            members = provider.GetAscendants(args.CubeName, args.SubCube, args.HierarchyUniqueName, args.StartLevelUniqueName, args.MemberUniqueName);

            return XmlUtility.Obj2XmlStr(members, Common.Namespace);
        }
    }
}
